package com.cloudpark.mqtt;

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;

/**
 * MQTT Subscriber
 * 
 * @author huixiao200068
 *
 */
public class MQTTSub {
    public static String doTest(int i) {
        try {

            // 创建MqttClient
            MqttClient client = new MqttClient(Configuration.TCPAddress, "scriber");

            // 回调处理类
            SubCallBack callback = new SubCallBack("scriber", i);
            client.setCallback(callback);

            // 创建连接可选项信息
            MqttConnectOptions conOptions = new MqttConnectOptions();
            conOptions.setCleanSession(Configuration.cleanSession);
            conOptions.setKeepAliveInterval(Configuration.keepAliveInterval);

            // 连接broker
            client.connect(conOptions);

            // 发布相关的订阅
            client.subscribe(Configuration.topic, Configuration.QoS);

            Scanner scan = new Scanner(System.in);
            for (String input = ""; !input.equalsIgnoreCase("q"); input = scan.nextLine())
                ;

            client.disconnect();

            System.out.println("Finished");
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        return "success";
    }

    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool(); 
         
        for(int i=0;i<1;i++){
            MyTask myTask = new MyTask(i);
            executor.execute(myTask);
//            System.out.println("线程池中线程数目："+executor.getPoolSize()+"，队列中等待执行的任务数目："+
//            executor.getQueue().size()+"，已执行玩别的任务数目："+executor.getCompletedTaskCount());
        }
//        executor.shutdown();
        
    }
    
}

class MyTask implements Runnable {

    private int i;
    
    public MyTask() {
        super();  
    }
    
    public MyTask(int i) {
        super();  
        this.i = i;
    }

    @Override
    public void run() {
        MQTTSub sub = new MQTTSub();
        sub.doTest(i);
    }
    
}
